<?php
namespace Users\Controller;

class MemberController extends CommonController{
	private $user;
	
	function _initialize(){
		parent::_initialize();
		$this->user = D('Users');
	}
	
	public function index(){
//		dump($_SESSION);
// 		dump(cookie());
		$uinfo = $this->user->find(session('loginUser.uid'));
		$this->assign('uinfo',$uinfo);
		$this->display();
	}
	
	public function info_post(){
		if(IS_POST){
			$_POST['update_time'] = Date('Y-m-d H:i:s');
			if($this->user->create()){
				if($this->user->save()){
					$info = $this->user->find(session('loginUser.uid'));
					//更新登录用户session()
					$user = new \Users\Service\LoginService();
					$user->createusersession($info);
					$this->success('保存成功',U('member/index'));
				}else{
					$this->error('保存失败');
				}
			}else{
				$this->error($this->user->getError());
			}
		}
	}
	
	//退出登录
	public function loginout(){
		$uid = session('loginUser.uid');

		session(null); //删除当前所有session
		cookie('member_username',null);
		cookie('member_pwd',null);

		//增加登出日志
		$userslog = new \Userslog\Service\LogService();
		$userslog->addLog($uid,'logout');

		$this->redirect('Login/index');
	}
	
	//修改密码
	public function pwd(){
		$this->display();
	}
	
	public function pwd_post(){
		if(IS_POST){
			$oldpwd = md5(trim($_POST['oldpwd']));
			$newpwd = md5(trim($_POST['newpwd']));
			$userinfo = $this->user->find(session('loginUser.uid'));
			if($oldpwd === $userinfo['password']){
				$data['uid'] = SESSION('loginUser.uid');
				$data['password'] = $newpwd;
				$data['update_time'] = date('Y-m-d H:i:s');
				if($this->user->create($data)){
					if($this->user->save()){
						$this->success('密码修改成功',U('member/pwd'));
					}else{
						$this->error('密码修改失败');
					}
				}
				
			}else{
				$this->error('原密码错误');
			}
		}
	}
	
	//判断密码是否正确
	public function checkoldpwd(){
		$userinfo = $this->user->find(session('loginUser.uid'));
		if($userinfo['password'] === md5($_REQUEST['oldpwd'])){
			echo '{"ok":"原密码正确"}';
		}else{
			echo  '{"error":"原密码不正确"}' ;
		}
	}
	
	//判断邮箱是否注册
	public function checkemail(){
		$email = trim($_REQUEST['email']);
		$map['email'] = $email;
		$map['uid'] = array('not in',session('loginUser.uid'));
		if($this->user->where($map)->find()){
			echo '{"error":"邮箱已被注册"}';
		}else{
			echo '{"ok":"邮箱可用"}';
		}
	}
	
}